package server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 *
 * @author Sasa
 */
public class Requests implements Runnable {

    Socket socket;
    DataBase db;
    BufferedReader in;
    BufferedWriter out;
    DataOutputStream dout;

    public Requests(Socket socket, DataBase db) throws Exception {
	this.socket = socket;
	this.db = db;

	this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
	this.out = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));
	this.dout = new DataOutputStream(this.socket.getOutputStream());
    }

    public void run() {
	try {
	    // start controller
	    this.handler();
	} catch (Exception e) {
	    System.out.println(e);
	}
    }

    public void handler() throws Exception {
	// BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));

	String line;
	String[] params;

	// Handle requests
	while ((line = in.readLine()) != null) {
	    System.out.println(line);
	    params = line.split("#");
	    // Komande

	    // LOGIN#username#password
	    if (params[0].equals("LOGIN")) {
		sendString(String.valueOf(db.checkLogin(params[1], params[2])));
	    } // TASKS
	    else if (params[0].equals("TASKS")) {
		sendXML(db.xmlTasks(Integer.parseInt(params[1])));
	    } // MEMBERS
	    else if (params[0].equals("MEMBERS")) {
		sendXML(db.xmlMembers());
	    } // COMPLETE#taskId
	    else if (params[0].equals("COMPLETE")) {
		sendResponse(db.completeTask(Integer.parseInt(params[1])));
	    } // NEWTASK#memberId#assigment
	    else if (params[0].equals("NEWTASK")) {
		sendResponse(db.addTask(Integer.parseInt(params[1]), params[2]));
	    }
	    // NEWMEMBER#username#passwordhash
	    else if (params[0].equals("NEWMEMBER")) {
		sendResponse(db.addMember(params[1], params[2]));
	    }
	}
    }

    public void sendResponse(Boolean response) throws Exception {

	out.write((response) ? "OK" : "ERROR");
	out.newLine();
	out.flush();
	// return (response) ? "OK" : "ERROR";
    }

    public void sendString(String str) throws Exception {

	out.write(str);
	out.newLine();
	out.flush();
    }

    public void sendXML(String filename) throws Exception {

	BufferedReader br = new BufferedReader(new FileReader(filename));
	String line;
	while ((line = br.readLine()) != null) {
	    out.write(line);
	    out.newLine();
	}
	out.newLine();
	out.flush();
    }
}
